#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BLKSIZE 1024

int copyfile(int fromfd, int tofd)
{
	int byread;
	int total_bytes = 0;
	char buf[BLKSIZE];
	while ((byread = read(fromfd, buf, BLKSIZE)) > 0) {
		if (write(tofd, buf, BLKSIZE) < 0) {
			fprintf(stderr, "write error");
			return -1;
		}
		total_bytes += byread;
	}
	return total_bytes;
}

int main(int argc, char **argv)
{
	int fd, fd1, fd2;
	pid_t tpid;
	int bytesread;

	if (argc != 3) {
		fprintf(stderr, "Argument error\n");
		return -1;
	}
	if ((fd1 = open(argv[1], O_RDONLY)) == -1) {
		fprintf(stderr, "open the first file error\n");
		return -1;
	}
	if ((fd2 = open(argv[2], O_RDONLY)) == -1) {
		fprintf(stderr, "open the first file error\n");
		return -1;
	}
	if ((tpid = fork()) == -1) {
		fprintf(stderr, "create process error\n");
		return -1;
	}
	if (tpid == 0) {
		fd = fd1;
	} else {
		wait();
		fd = fd2;
	}
	bytesread = copyfile(fd, 1);
	fprintf(stderr, "Bytes read: %d\n", bytesread);
	return 0;
}
